package br.com.triad.testelucasdsniel;

import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class MyCustomMapView extends MapView {

	public MyCustomMapView(Context context, String apiKey) {
		super(context, apiKey);
	}

	public MyCustomMapView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MyCustomMapView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public interface OnLongpressListener {
		public void onLongpress(MapView view, GeoPoint longpressLocation);
	}

	public void setOnLongpressListener(MyCustomMapView.OnLongpressListener listener) {
		longpressListener = listener;
	}

	// @Override
	public boolean onTouchEvent(MotionEvent ev) {
		handleLongpress(ev);

		return super.onTouchEvent(ev);
	}

	private void handleLongpress(final MotionEvent event) {

		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			longpressTimer = new Timer();
			longpressTimer.schedule(new TimerTask() {
				@Override
				public void run() {
					GeoPoint longpressLocation = getProjection().fromPixels((int) (event.getX() * 1E6), (int) (event.getY() * 1E6));
					longpressListener.onLongpress(MyCustomMapView.this, longpressLocation);
				}

			}, LONGPRESS_THRESHOLD);
			lastMapCenter = getMapCenter();
		}
		if (event.getAction() == MotionEvent.ACTION_MOVE) {
			if (!getMapCenter().equals(lastMapCenter)) {
				longpressTimer.cancel();
			}
			lastMapCenter = getMapCenter();
		}

		if (event.getAction() == MotionEvent.ACTION_UP) {
			longpressTimer.cancel();
		}
		if (event.getPointerCount() > 1) {
			longpressTimer.cancel();
		}
	}

	static final int LONGPRESS_THRESHOLD = 500;
	private GeoPoint lastMapCenter;
	private Timer longpressTimer = new Timer();
	private MyCustomMapView.OnLongpressListener longpressListener;
}
